/**
 * Created by user on 2015/9/23.
 */

var secondHandService = require('../../../services/mis/market/secondHandService');
var messageUtil = require('../../../common/utils/messageUtil');
var toolUtil = require('../../../common/utils/toolUtil');
var nodeExcel = require('excel-export');
var redisKey = require('../../../config/redisKey');

exports.secondHandList = function(req, res) {

    secondHandService.secondHandListService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when secondHandList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when secondHandList...'));
        }else {
            var data = {
                count:results[1]["count"],
                totalPage: results[1]["totalPage"],
                list: results[2]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }

    });
};


exports.getGoodsCategory = function(req, res) {

    secondHandService.getGoodsCategoryService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when secondHandList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when secondHandList...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }

    });
};

exports.deleteSecondHand = function(req, res) {

    secondHandService.deleteSecondHandService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when deleteSecondHand...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when deleteSecondHand...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};


exports.updateSecondHand = function(req, res) {

    secondHandService.updateSecondHandService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when updateSecondHand...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when updateSecondHand...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};

exports.getReplyList = function(req, res) {

    secondHandService.getReplyListService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when secondHandList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when secondHandList...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }

    });
};


exports.exportSecondHand = function (req, res) {

    var input = req.cparams;
    logger.debug(input);
    //var page = req.params.page;
    //var size = req.params.size;

    secondHandService.exportSecondHandService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when exporUserScore...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when exporUserScore...'));
        } else {

            if(!results[1]) {
                logger.error('Exception happen when exporUserScore...导出数据为0' + err.message);
                res.json(messageUtil.composeSucceededMessage(req, null, {}));
            }else {
                var conf = {};

                conf.cols = [{
                    caption: '商品类别',
                    type: 'string'
                }, {
                    caption: '所属小区',
                    type: 'string'
                },
                {
                    caption: '标题',
                    type: 'string'
                },
                {
                    caption: '描述',
                    type: 'string'
                },
                {
                    caption: '回复次数',
                    type: 'string'
                },
                {
                    caption: '创建者',
                    type: 'string'
                },
                {
                    caption: '创建者ID',
                    type: 'string'
                },
                {
                    caption: '创建者手机号',
                    type: 'string'
                },{
                    caption: '创建者注册时间',
                    type: 'string'
                },
                {
                    caption: '创建时间',
                    type: 'string'
                },
                    {
                    caption: '发布时间',
                    type: 'string'
                }, {
                    caption: '价格',
                    type: 'number'
                }, {
                    caption: '状态',
                    type: 'string'
                }];
                //logger.debug(results[1]);
                var data = results[1];
                var tempRows = new Array();
                logger.debug(data.length);
                for (var i = 0; i < data.length; i++) {
                    var temp = new Array();
                    logger.debug(data[i].category);
                    if(data[i].category){
                        temp.push(data[i].category.name);
                    }else{
                        temp.push('');
                    }
                    if(data[i].community)temp.push(data[i].community.communityName);
                    temp.push(data[i].title);
                    temp.push(data[i].desc);
                    if(data[i]._doc.replyCount) {
                        temp.push(data[i]._doc.replyCount);
                    }else{
                        temp.push("0");
                    }
                    //temp.push(data[i].replies.length+"");
                    if(data[i].createdBy) {
                        temp.push(data[i].createdBy.nickName);
                        temp.push(data[i].createdBy._id.toString());
                        temp.push(data[i].createdBy.mobilePhone);
                    }else{
                        temp.push("");
                        temp.push("");
                        temp.push("");
                    };
                    if(data[i].createdBy) {
                        //temp.push(data[i].createdBy.dateCreated);
                        var dateCreated = new Date(data[i].createdBy.dateCreated);
                        temp.push(dateCreated.getFullYear() + "-" + (dateCreated.getMonth() + 1) + "-" + dateCreated.getDate() + " " + dateCreated.getHours() + ":" + dateCreated.getMinutes());
                    }else{
                        temp.push("");
                    };

                    if (data[i].dateCreated != null) {
                        var dateCreated = new Date(data[i].dateCreated);
                        temp.push(dateCreated.getFullYear() + "-" + (dateCreated.getMonth() + 1) + "-" + dateCreated.getDate() + " " + dateCreated.getHours() + ":" + dateCreated.getMinutes());
                    } else {
                        temp.push("");
                    };

                    if (data[i].releaseDate != null) {
                        var releaseDate = new Date(data[i].releaseDate);
                        temp.push(releaseDate.getFullYear() + "-" + (releaseDate.getMonth() + 1) + "-" + releaseDate.getDate() + " " + releaseDate.getHours() + ":" + releaseDate.getMinutes());
                    } else {
                        temp.push("");
                    };

                    temp.push(data[i].presentPrice);
                    //logger.debug(data[i].presentPrice);
                    if(data[i].dealStatus) {
                        temp.push(data[i].dealStatus == 0 ? '未交易' : '已交易');
                    }else{
                        temp.push('未交易');
                    }
                    //logger.debug(data[i].dealStatus);

                    tempRows.push(temp);

                    //logger.debug(tempRows);
                };


                conf.rows = tempRows;

                var ret = nodeExcel.execute(conf);
                res.setHeader('Content-Type', 'application/vnd.openxmlformats');
                res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
                res.end(ret, 'binary');
            }
        };

    });


}

exports.handleLevel = function(req, res) {

    secondHandService.handleLevelService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when handleLevel...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when handleLevel...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};

exports.handleSale = function(req, res) {

    secondHandService.handleSaleService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when handleSale...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when handleSale...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};

exports.secondHandReplyList = function(req, res) {

    secondHandService.secondHandReplyListService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when secondHandReplyList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when secondHandReplyList...'));
        }else {
            var data = {
                count:results[0]["count"],
                totalPage: results[0]["totalPage"],
                list: results[1]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }

    });
};


exports.deleteSecondHandReply = function(req, res) {

    secondHandService.deleteSecondHandReplyService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when deleteReply...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when deleteReply...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));

           //扣情值
            toolUtil.hessianInvokeAddScore( req.body.replyBy, 32, null, function (value) {

            });

            //统计用户数据
            redisClient.HINCRBY(redisKey.getUserDataStatisticKey(req.body.replyBy), 'goodsReply', -1);
        }

    });
};